package com.estronger.shopmanage.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.widget.ImageView;

import com.lidroid.xutils.BitmapUtils;

public class BitmapHelper {
	private BitmapHelper() {
	}

	private static BitmapUtils bitmapUtils;

	/**
	 * BitmapUtils并不是一个单列模式，在项目中将它封装成单列
	 * 
	 * @param appContext
	 *            application context
	 * @return
	 */
	public static BitmapUtils getBitmapUtils() {
		if (bitmapUtils == null) {
			bitmapUtils = new BitmapUtils(UiUtils.getContext(), FileUtils
					.getIconDir().getAbsolutePath(), 0.3f);
		}
		return bitmapUtils;
	}

	/**
	 * 计算出图片的宽高比，并进行缩放调整
	 * 
	 * @param op
	 *            缩放选择条件
	 * @param reqWidth
	 *            需要的宽度
	 * @param reqheight
	 *            需要的高度
	 * @return inSampleSize 缩放的倍数
	 */
	public static int calculateInSampleSize(BitmapFactory.Options op, int reqW,
			int reqH) {
		int originalWidth = op.outWidth;
		int originalHeight = op.outHeight;
		int inSampleSize = 1;// 默认是一倍 inSampleSize=2时就是缩小一倍
		if (originalWidth > reqW || originalHeight > reqH) {
			int halfW = originalWidth / 2;
			int halfH = originalHeight / 2;
			while ((halfW / inSampleSize > reqW)
					&& (halfH / inSampleSize > reqH)) {
				inSampleSize *= 2;
			}
		}
		return inSampleSize;
	}

	private static BitmapFactory.Options option;

	/**
	 * 图片缩放显示
	 * 
	 * @param pathName
	 *            图片的路径
	 * @param iv
	 *            展示的ImageView
	 */
	public static void displayImg(String pathName, ImageView iv,
			boolean isCamera) {
		if (null == option) {
			option = new Options();
		}
		option.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(pathName, option);
		option.inPreferredConfig = Bitmap.Config.ARGB_4444;
		if (isCamera) {//
			option.inSampleSize = 10;
		} else {
			option.inSampleSize = calculateInSampleSize(option, 20, 26);
		}

		option.inJustDecodeBounds = false;
		Bitmap bitmap = BitmapFactory.decodeFile(pathName, option);
		iv.setImageBitmap(bitmap);
	}
}
